"""
    This file is part of Athedyn's Tale.

    Athedyn's Tale is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Athedyn's Tale is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Athedyn's Tale.  If not, see <http://www.gnu.org/licenses/>.
"""

import time, random, pickle, thread, os
from rpgObject import rpgObject
from commands import Commands
from attackcommands import ACommands
from sys import platform, exit

try:
	import MySQLdb
except:
	print "Please install MySQLdb"
	exit()
	

if platform.startswith('win'):
    from winsound import PlaySound, SND_FILENAME, SND_ASYNC


class Main(rpgObject):
    def playSound(self, file):
        if platform.startswith('win'):
            try:    
                file = 'sounds/' + file
                PlaySound(file, SND_FILENAME|SND_ASYNC)
            except:
                pass
    def load(self):
        try:
            saveFile = open('rpg.sav')
            save = pickle.load(saveFile)
            return save
        except:
            "New game starting"
            return 0

    def save(self):
        try:
            objs = self.objects['user'].objects
            del self.objects['user'].objects            
            saveFile = open('rpg.sav', 'w')
            pickle.dump(self.objects['user'], saveFile)
            print "Saved"
            self.objects['user'].objects = objs
        except:
            print "Could not save"
        
class Attack(rpgObject):
    def __init__(self):
        rpgObject.__init__(self)
        self.addStat('inBattle', 0)
        
    def enemyHit(self):
        #enemy hits you
        successRate = self.objects['user'].statistics['dexterity'] - self.objects['enemy'].statistics['dexterity']
        rollToHit = random.randint(1,100)
        percent = random.randint(0,100)
        #print "They rolled a %d\nThey needed above %d" % (rollToHit, successRate)
        if self.objects['enemy'].statistics['effect'][1] > 0:
            effect = self.objects['enemy'].statistics['effect'][0]
            if self.objects['enemy'].statistics['effect'][1] > 0:
                ableToFight = self.objects['magic'].statistics['spellEffects'][effect](self.objects['enemy'])
                self.objects['enemy'].statistics['effect'][1] -= 1
                if self.objects['enemy'].statistics['health'] <= 0:
                    return
                if ableToFight == 0:
                    return
        if rollToHit > successRate:
            print "They hit you"
            hitForEnemy = round(self.objects['enemy'].statistics['strength'] - (self.objects['user'].statistics['defense'] * (percent/100.)))
            if (hitForEnemy >= 0):
                self.objects['user'].statistics['health'] = self.objects['user'].statistics['health'] - hitForEnemy
            else:
                hitForEnemy = 0
        else:
            hitForEnemy = 0
            print "They missed"
        print "They hit for %d.  You are now at %d HP" % (hitForEnemy, self.objects['user'].statistics['health'])
    
    def hit(self, damageModifier):#, user, enemy):
        #you hit enemy
        successRate = self.objects['enemy'].statistics['dexterity'] - self.objects['user'].statistics['dexterity']
        rollToHit = random.randint(1,100)
        #print "You rolled a %d" % rollToHit
        if rollToHit > successRate:
            hitForUser = round(self.objects['user'].statistics['strength'] + (int(self.objects['items'].statistics['weaponType'][self.objects['user'].statistics['weapon']][1]) * damageModifier))
            self.objects['enemy'].statistics['health'] = self.objects['enemy'].statistics['health'] - hitForUser
            self.objects['items'].types[str(self.objects['aCommands'].statistics['typeOfAttack'])]()
        else:
            hitForUser = 0
        
        if self.objects['enemy'].statistics['health'] < 0:
            self.objects['enemy'].statistics['health'] = 0
        
        percentDead = float(self.objects['enemy'].statistics['health']) / self.objects['enemy'].statistics['maxHealth']
        if percentDead >= 0:
            howDead = "dying"
        if percentDead >= .2:
            howDead = "very tired"
        if percentDead >= .4:
            howDead = "falling over"
        if percentDead  >= .6:
            howDead = "slowing down"
        if  percentDead >= .8:
            howDead = "fine"
           
        print "You hit for %d.  They are %s." % (hitForUser, howDead)
        
    def attack(self):
        self.statistics['inBattle'] = 1
        print "A %s is about to attack you." % self.objects['enemy'].name
        #self.objects['user'].status(0)
        #self.objects['enemy'].status()
        while (self.objects['enemy'].statistics['health'] > 0): 
            answer = raw_input(self.objects['user'].prompt())
            while answer == "":
                answer = raw_input(self.objects['user'].prompt())
            for key, item in self.commands.items():
                if answer.split()[0] == key:
                    args = {}
                    args['message'] = answer.replace(answer.split()[0] + " ", "")
                    enemyAttack = item(args)
                    if self.objects['enemy'].statistics['health'] >= 0 | enemyAttack == 1:
                        self.enemyHit()
                    break
            if self.objects['user'].statistics['health'] <= 0:
                print "You lost.  Game Over"
                time.sleep(2)
                return ""
        print "You win!"
        self.objects['area'].statistics['respawnLast'][self.objects['area'].ID] = int(time.time())
        self.objects['user'].statistics['experience'] = self.objects['enemy'].statistics['experience'][self.objects['area'].statistics['enemyID']] + self.objects['user'].statistics['experience']
        self.objects['area'].statistics['enemyIsThere'][self.objects['area'].statistics['enemyID']] = 0
        self.objects['area'].statistics['enemyDiedIn'] = self.objects['area'].ID
        self.objects['user'].levelUp()
        self.statistics['inBattle'] = 0
    
    def commandSetup(self):
        command = self.objects['aCommands']
        self.commands['slash'] = command.slash
        self.commands['stab'] = command.stab
        self.commands['bludgeon'] = command.bludgeon
        self.commands['strike'] = command.strike
        self.commands['help'] = command.help
        self.commands['run'] = command.run
        self.commands['defend'] = command.defend
        self.commands['use'] = self.objects['commands'].use
        self.commands['cast'] = self.objects['commands'].cast
        
#ID NAME NORTH EAST SOUTH WEST ZONEAREAID ENEMY ITEM DESCRIPTION
class Area(rpgObject):
    def __init__(self):        
        global enemy
        global Continue
        global commands
        global zoneID
        self.commands = {}
        self.Continue = 1
        

        rpgObject.__init__(self)
        self.readZones()
        self.setUp()
        
    def setUp(self):
        self.addStat('areas', [])
        self.addStat('names', {})
        self.addStat('respawnLast', {})
        self.addStat('enemyIsThere', {})
        self.addStat('enemyDiedIn', 0)
        self.addStat('exits', {"north": 0,"east": 0,"south": 0,"west": 0})
        self.addStat('zoneChangeID', [])
        self.addStat('enemyID', 0)
        self.addStat('quest', 0)
        self.addStat('special', 0)
        self.name = "None"
        self.ID = 0
        self.description = "No Description"
        self.addStat('mapList', [])
        
    def readZones(self):
        openFile = 'text/zones.txt'
        data = open(openFile)
        self.addStat('zones', [])
        tempStats = data.readlines()
        for id in range(0, len(tempStats)):
            self.statistics['zones'].append(tempStats[id].split('|')[1])
        
    def readStats(self, zoneID):
        self.zoneID = zoneID
        self.objects['user'].statistics['zone'] = self.zoneID
        zone = self.statistics['zones'][zoneID]
        
        
        #splits the name of the zone if it's more than one word.
        zone = zone.split()[0]
        #Loads the zone data from first part of name
        openFile = 'text/zones/' + zone.lower() + '.txt'
        data = open(openFile)
        self.statistics['areas'] = data.readlines()
        tempStats = {}
        self.statistics['mapList'] = []
        
        
        #extracts the data into a temp so i can get the names
        for stats in range(0,len(self.statistics['areas'])):
            tempStats[stats] = self.statistics['areas'][stats].split('|')
            
        #pulls the names out of the temp and stores them into names
        #print tempStats
        for num in range(0,len(self.statistics['areas'])):
            self.statistics['names'][num] = tempStats[num][1]
            self.statistics['respawnLast'][num] = 0
            self.statistics['enemyIsThere'][num] = 1
            self.statistics['mapList'].append(map(int, tempStats[num][4].split(',')))
        
        try:
            self.setUpItems()
        except:
            pass        
        
    def new(self, ID, zoneChangeDirection):
        if str(ID)[0:2] == '99':
            if len(str(ID)) >= 3:
                #loads the new zone, only takes the number after 99
                self.readStats(int(str(ID)[2:len(str(ID))]))
                #sets the ID back to the new area
                ID = self.statistics['zoneChangeID'][zoneChangeDirection]
        self.ID = ID
        self.objects['user'].statistics['lastArea'] = self.ID
        #splits line into array
        tempStats = self.statistics['areas'][ID].split('|')
        #name
        self.name = tempStats[1]
        #sets up the exits array
        tempStats[2] = tempStats[2].split(',')
        self.statistics['exits'] = {"north": int(tempStats[2][0]), 
                                    "east": int(tempStats[2][1]), 
                                    "south": int(tempStats[2][2]), 
                                    "west": int(tempStats[2][3])}
        try:
            tempStats[3] = tempStats[3].split(',')
            self.statistics['zoneChangeID'] = {"north": int(tempStats[3][0]), 
                                               "east": int(tempStats[3][1]), 
                                               "south": int(tempStats[3][2]), 
                                               "west": int(tempStats[3][3])}
        except:
            pass
        
        #sets up the enemies in the room
        self.statistics['enemyID'] = int(tempStats[6])
        
        #splits it by ; so that there can be more than one special thing in the area
        self.statistics['special'] = tempStats[5].split(';')
        
        tempSpecial = []
        for special in self.statistics['special']:
            #splits it by ',' next so that it can get what special thing and the id for it
            tempSpecial.append(map(int, special.split(',')))
            
        self.statistics['special'] = tempSpecial
        #sets up the description
        self.description = tempStats[8]
        
        #setups up the map
        #first sets the current location
        self.objects['user'].statistics['currentLocation'] = [int(tempStats[4].split(',')[0]), int(tempStats[4].split(',')[1])]
        #populates the map, sets the coord to 1 so that it can be displayed on the map function
        self.objects['user'].statistics['mapArray'][self.zoneID][self.statistics['mapList'][self.ID][0]][self.statistics['mapList'][self.ID][1]] = 1
        self.printDescription()
        

    def setUpItems(self):
        #print self.zoneID
        if self.objects['user'].statistics['areaItemsSetup'][self.zoneID] == 0:
            self.objects['user'].statistics['areaItemsSetup'][self.zoneID] = 1
            for ID in range(0, len(self.statistics['areas'])):
                items = self.statistics['areas'][ID].split('|')[7].split(',')
                self.objects['user'].statistics['areaItems'][self.zoneID].append(items)
    
    def printDescription(self):
        print "You are in %s." % self.name
        print self.description
        print

        north, south, east, west = "","","",""
        if self.statistics['exits']['north'] > 0:
            north = 'north '
        if self.statistics['exits']['east'] > 0:
            east = 'east '
        if self.statistics['exits']['south'] > 0:
            south = 'south '
        if self.statistics['exits']['west'] > 0:
            west = 'west '
        
        timeBetween = int(time.time()) - self.statistics['respawnLast'][self.ID] + self.objects['enemy'].statistics['randomRespawn']
        if timeBetween > self.objects['enemy'].statistics['respawnTime'][self.statistics['enemyID']]:
            enemyText = self.objects['enemy'].statistics['names'][self.statistics['enemyID']]
        else:
            enemyText = "None"
        itemsInArea = "Items in the area:"
        #print self.objects['user'].statistics['areaItems'][self.ID]
        #print self.objects['items'].statistics['names']
        for item in self.objects['user'].statistics['areaItems'][self.zoneID][self.ID]:
            if int(item) > 0:
                itemsInArea = itemsInArea + " " + self.objects['items'].statistics['names'][int(item)]
            if int(item) == 0:
                itemsInArea = itemsInArea + " None"
        if len(self.objects['user'].statistics['areaItems'][self.zoneID][self.ID]) == 0:
            itemsInArea = itemsInArea + " None"
        
        people = ""        
        for item in self.statistics['special']:
            key = self.statistics['special'].index(item)
            if int(self.statistics['special'][key][0]) > 0:
                if int(self.statistics['special'][key][0]) == 1:
                    people += " " + self.objects['quest'].statistics['giver'][int(self.statistics['special'][key][1])]
                if int(self.statistics['special'][key][0]) == 2:
                    people += " " + self.objects['shop'].statistics['owner'][int(self.statistics['special'][key][1])]
            else:
                people += " No one"
        
        
        print itemsInArea
        print "People in the area:%s" % people
        print "The enemies in the area are: %s" % enemyText
        print "Exits: %s%s%s%s" % (north, east, south, west)
         

    def moveArea(self):    
 
        moveTo = raw_input(self.objects['user'].prompt())
       
        while moveTo == "":
            moveTo = raw_input(self.objects['user'].prompt())
        #return continue variable, then the ID of an enemy if going to attack
        for key, item in self.commands.items():
            if moveTo.split()[0] == key:
                args = {}
                args['message'] = moveTo.replace(moveTo.split()[0] + " ", "")
                newArea, enemyAttack = item(args)
                break
            newArea = 0
            enemyAttack = 0

        if enemyAttack > 0:
            return self.Continue, self.statistics['enemyID']

        #checks to see what kind of quests there are, and if a special thing happens from one of them.  ex. blocking your path
        for item in self.statistics['special']:
            key = self.statistics['special'].index(item)
            if int(item[0]) > 0:
                if int(item[0]) == 1:
                    restriction = self.objects['quest'].statistics['restriction'][int(item[1])]
                    if int(restriction[0]) == 1:
                        if self.objects['user'].statistics['quests'][int(item[1])] == 0:
                            if restriction[1] == moveTo.split()[0]:
                                print 'block'
                                args = [newArea, moveTo]
                                newArea = self.objects['quest'].statistics['types'][int(restriction[0])](int(item[1]), args)
        if newArea == 0:
            print "Not a command or area"
            return self.Continue,0
        elif newArea == -1:
            return self.Continue,0
        else:
            #user.statistics['lastArea'] = newArea
            self.new(newArea, moveTo.split(' ')[0])
            #return Continue, no enemy
            return 1,0

    def respawn(self):
        while self.Continue:
            timeBetween = int(time.time()) - self.statistics['respawnLast'][self.statistics['enemyDiedIn']] + enemy.statistics['randomRespawn']
            if timeBetween > enemy.statistics['respawnTime'][self.statistics['enemyID']]:
                if self.statistics['enemyIsThere'][self.statistics['enemyID']] == 0:
                    enemyText = enemy.statistics['names'][self.statistics['enemyID']]
             
                    if self.ID == self.statistics['enemyDiedIn']:
                        print "%s has returned" % enemyText
                     
                    self.statistics['enemyIsThere'][self.statistics['enemyID']] = 1

    def commandSetup(self):
        #sets up the Commands that are available for the user.  Each command is a link to the function in an instance.
        command = self.objects['commands']
        #This command has no use as of yet, so why bother using it?
        #self.commands['say'] = command.say
        self.commands['north'] = command.goNorth
        self.commands['south'] = command.goSouth
        self.commands['east'] = command.goEast
        self.commands['west'] = command.goWest
        self.commands['help'] = command.help
        self.commands['quit'] = command.quit
        self.commands['attack'] = command.attack
        self.commands['inventory'] = command.inventory
        self.commands['use'] = command.use
        self.commands['cast'] = command.cast
        self.commands['spells'] = command.spells
        self.commands['status'] = command.status
        self.commands['look'] = command.look
        self.commands['map'] = command.map
        self.commands['save'] = command.save
        self.commands['take'] = command.take
        self.commands['give'] = command.give
        self.commands['buy'] = command.buy
        self.commands['sell'] = command.sell
        self.commands['help'] = command.help
        self.commands['talk'] = command.talk
        
    def map(self):
        for a in range(0,7):
            toPrint = ""
            for b in range(0,7):
                if self.objects['user'].statistics['mapArray'][self.zoneID][a][b] == 0:
                    toPrint = toPrint + "   "
                if self.objects['user'].statistics['mapArray'][self.zoneID][a][b] == 1:
                    if self.objects['user'].statistics['currentLocation'][0] == a:
                        if self.objects['user'].statistics['currentLocation'][1] == b:
                            toPrint = toPrint + "[X]"
                        else:
                            toPrint = toPrint + "[ ]"
                    else:
                        toPrint = toPrint + "[ ]"
            print toPrint

class Jobs(rpgObject):
    def __init__(self):
        rpgObject.__init__(self)
        self.addStat('barbarian', {'health': 12, 'magic': 1, 'strength': 5, 'defense': 3, 'dexterity': 2, 'job': 'barbarian', 'weapon': 6, 'hpRegen': 3, 'mpRegen': .1, 'spellList': [0],
                    'spellListLevels': [],
                    'levelUp': [0.75,0.2,0.6,0.5,0.4]})
        self.addStat('fencer', {'health': 10, 'magic': 5, 'strength': 3, 'defense': 4, 'dexterity': 5, 'job': 'fencer', 'weapon': 5, 'hpRegen': 1, 'mpRegen': 2, 'spellList': [0],
                    'spellListLevels': [],
                    'levelUp': [0.55,0.4,0.5,0.45,0.55]})
        self.addStat('fighter', {'health': 11, 'magic': 3, 'strength': 4, 'defense': 4, 'dexterity': 3, 'job': 'fighter', 'weapon': 4, 'hpRegen': 2, 'mpRegen': 1, 'spellList': [0],
                    'spellListLevels': [],
                    'levelUp': [0.65,0.3,0.55,0.5,0.45]})
        self.addStat('wizard', {'health': 8, 'magic': 15, 'strength': 2, 'defense': 2, 'dexterity': 4, 'job': 'wizard', 'weapon': 7, 'hpRegen': .1, 'mpRegen': 3, 'spellList': [1,2],
                    'spellListLevels': [[],[],[3,4]],
                    'levelUp': [0.5,0.75,0.4,0.5,0.6]})

    def chose(self, weapon):
        print "Which class do you want to be?"
        print "You can be a fighter, fencer, wizard or a barbarian."
        choice = raw_input()
        jobs = ['fighter', 'fencer', 'barbarian', 'wizard']
        
        for job in jobs:
            if choice.lower() == job:
                self.showStats(choice, weapon)
                return self.statistics[choice] 
        return self.chose(weapon)
    
    def showStats(self, job, weapon):
        print "You chose to be a %s" % job
        print "The statistics for a %s are:" % job
        print "Health: %d" % self.statistics[job]['health']
        print "Magic: %d" % self.statistics[job]['magic']
        print "Strength: %d\nDefense: %d\nDexterity: %d" % ( self.statistics[job]['strength'], self.statistics[job]['defense'], self.statistics[job]['dexterity'])
        print "Your weapon would be a %s" % weapon.statistics['names'][self.statistics[job]['weapon']]
        choice = raw_input("Are you sure you want to be a %s? " % job)
        if choice.lower() == 'yes':
            print
            print
            return self.statistics[job]
        elif choice.lower() == 'no':
            return self.chose(weapon)

class User(rpgObject):
    def new(self, statistic):
        #Creates the user's statistics
        self.addStat('inventory', [1, 2, 6])
        self.addStat('health', statistic['health'])
        self.addStat('maxHealth', statistic['health'])
        self.addStat('magic', statistic['magic'])
        self.addStat('maxMagic', statistic['magic'])
        self.addStat('strength', statistic['strength'])
        self.addStat('defense', statistic['defense'])
        self.addStat('job', statistic['job'])
        self.addStat('dexterity', statistic['dexterity'])
        self.addStat('weapon', statistic['weapon'])
        self.addStat('hpRegen', statistic['hpRegen'])
        self.addStat('mpRegen', statistic['mpRegen'])
        self.addStat('spellList', statistic['spellList'])
        self.addStat('spellListLevels', statistic['spellListLevels'])
        self.addStat('levelUp', statistic['levelUp'])
        self.addStat('experience', 0)
        self.addStat('gold', 50)
        self.addStat('level', 1)
        self.addStat('lastArea', 1)
        self.addStat('currentLocation', [3,3])
        self.addStat('zone', 1)
        self.addStat('areaItems', [])
        self.addStat('areaItemsSetup', [])
        self.addStat('mapArray', [])
        self.addStat('quests', [])
        
        
    def setUpMap(self):
        for item in self.objects['area'].statistics['zones']:
            self.statistics['mapArray'].append([])
            for i in range(0,7):
                key = self.objects['area'].statistics['zones'].index(item)
                self.statistics['mapArray'][key].append([0,0,0,0,0,0,0])
    
    def setUpQuest(self):
        for item in self.objects['quest'].statistics['giver']:
            self.statistics['quests'].append(0)
    
    def setUpItems(self):
        for num in range(0, len(self.objects['area'].statistics['zones'])):
            self.statistics['areaItemsSetup'].append(0)
            self.statistics['areaItems'].append([])
        #print self.statistics['areaItemsSetup']
        #print self.statistics['areaItems']
        
    def status(self, howMuch):
        #if howMuch > 0: #so it can only show health at some points
        print "You are level %d" % self.statistics['level']
        print "You are a %s" % self.statistics['job']
        print "Your strength is: %d" % self.statistics['strength']
        print "Your defense is: %d" % self.statistics['defense']
        print "Your dexterity is: %d" % self.statistics['dexterity']
        print "You have %d xp" % self.statistics['experience']
        print "You are weilding a %s" % self.objects['items'].statistics['names'][self.statistics['weapon']]
            
    def items(self):
        print "You have %d gold" % self.statistics['gold']
        print "In your inventory you have the following:"
        for item in self.statistics['inventory']:
            print self.objects['items'].statistics['names'][int(item)]
        if len(self.statistics['inventory']) == 0:
            print "Nothing"

    def levelUp(self):
        if self.statistics['level'] >= 40:
            print "Max level"
            return
    
        experienceNeeded = 0
        for i in range(1,self.statistics['level'] + 1):
            experienceNeeded += i * 100
            
        if self.statistics['experience'] >= experienceNeeded:
            level = self.statistics['level']
            self.statistics['level'] += 1
            
            increase = level * self.statistics['levelUp'][0]
            if increase < 1: increase = 1
            self.statistics['health'] = round(self.statistics['health'] + increase)
            self.statistics['maxHealth'] = round(self.statistics['maxHealth'] + increase)
            self.statistics['hpRegen'] *= self.statistics['levelUp'][0]
            
            increase = level * self.statistics['levelUp'][1]
            if increase < 1: increase = 1
            self.statistics['magic'] = round(self.statistics['magic'] + increase)
            self.statistics['maxMagic'] = round(self.statistics['maxMagic'] + increase)
            self.statistics['mpRegen'] *= self.statistics['levelUp'][1]
            
            increase = level * self.statistics['levelUp'][2]
            if increase < 1: increase = 1
            self.statistics['strength'] = round(self.statistics['strength'] + increase)
            
            increase = level * self.statistics['levelUp'][3]
            if increase < 1: increase = 1
            self.statistics['defense'] = round(self.statistics['defense'] + increase)
            
            increase = level * self.statistics['levelUp'][4]
            if increase < 1: increase = 1
            self.statistics['dexterity'] = round(self.statistics['dexterity'] + increase)
            
            try:
                self.statistics['spellList'].extend(self.statistics['spellListLevels'][self.statistics['level']])
            except:
                pass
            print "You leveled"
            self.levelUp()
        else:
            pass
    def regen(self):
        while self.objects['area'].Continue:
            time.sleep(10)
            if self.objects['attack'].statistics['inBattle'] == 0:
                self.statistics['health'] += self.statistics['hpRegen']
                self.statistics['magic'] += self.statistics['mpRegen']
                if self.statistics['health'] > self.statistics['maxHealth']:
                    self.statistics['health'] = self.statistics['maxHealth']
                if self.statistics['magic'] > self.statistics['maxMagic']:
                    self.statistics['magic'] = self.statistics['maxMagic']
                
    def prompt(self):
        return "<HP: %d/%d MP: %d/%d >" % (self.statistics['health'], self.statistics['maxHealth'], self.statistics['magic'], self.statistics['maxMagic'])
        

#Enemy is close, but too far away to be a subclass of user
#ID NAME HEALTH STRENGTH DEXTERITY RESPAWN XP
class Enemy(rpgObject):
    global names
    
    def __init__(self):
        rpgObject.__init__(self)
        
        self.readStats()
        
    def new(self, ID):
        tempStats = self.statistics['enemies'][ID].split('|')
        self.ID = ID
        self.name = tempStats[1]
        self.statistics['dexterity'] = int(tempStats[4])
        self.statistics['health'] = int(tempStats[2])
        self.statistics['maxHealth'] = int(tempStats[2])
        self.statistics['strength'] = int(tempStats[3])
        #effect, time left, damage
        self.statistics['effect'] = [0,0,0]
        self.statistics['randomRespawn'] = random.randint(-4,4)
        
    def status(self):
        print "The enemy's HP is: %d" % self.statistics['health']
        
    def readStats(self):
        openFile = 'text/enemies.txt'
        data = open(openFile)
        self.addStat('enemies', data.readlines())
        tempStats = range(0,len(self.statistics['enemies']))
        self.addStat('names', range(0,len(self.statistics['enemies'])))
        self.addStat('experience', range(0,len(self.statistics['enemies'])))
        #extracts the data into a temp so i can get the names
        for stats in range(0,len(self.statistics['enemies'])):
            tempStats[stats] = self.statistics['enemies'][stats].split('|')
        #pulls the names out of the temp and stores them into names
        self.addStat('respawnTime', range(0,len(self.statistics['enemies'])))
        for name in range(0, len(self.statistics['enemies'])):
            self.statistics['names'][name] = tempStats[name][1]
            self.statistics['respawnTime'][name] = int(tempStats[name][5])
            self.statistics['experience'][name] = int(tempStats[name][6])
        self.addStat('randomRespawn', 0)
        self.addStat('dexterity', 0)
        self.addStat('effect', [0,0,0])


class Items(rpgObject):
    def __init__(self):
        rpgObject.__init__(self)
        self.readStats()
        self.setTypes()
        
    def readStats(self):
        openFile = 'text/items.txt'
        data = open(openFile)
        self.addStat('items', data.readlines())
        self.addStat('names', [])
        self.addStat('itemEffect', [])
        self.addStat('weaponType', [])
        self.addStat('armorType', [])
        self.addStat('cost', [])
        self.addStat('description', [])
        
        tempStats = []
        
        for item in self.statistics['items']:
            tempStats.append(item.split('|'))
            
        #1.ID|2.Name|3.Effects|4.WeaponType,Strength|5.ArmorType,Defense|6.Cost|7.Description|
        for item in tempStats:
            self.statistics['names'].append(item[1])
            self.statistics['itemEffect'].append(item[2].split(','))
            self.statistics['weaponType'].append(item[3].split(','))
            self.statistics['armorType'].append(item[4].split(','))
            self.statistics['cost'].append(int(item[5]))
            self.statistics['description'].append(item[6])
        
    #Items
    def effect(self, ID):
        if int(self.statistics['itemEffect'][ID][0]) == 1:
            self.heal(ID)

        if int(self.statistics['itemEffect'][ID][0]) == 2:
            self.magicUp(ID)

    def heal(self, ID):
        self.objects['user'].statistics['health'] = self.objects['user'].statistics['health'] + int(self.statistics['itemEffect'][ID][1])
        if self.objects['user'].statistics['health'] > self.objects['user'].statistics['maxHealth']:
            self.objects['user'].statistics['health'] = self.objects['user'].statistics['maxHealth']
        print "You healed %d" % int(self.statistics['itemEffect'][ID][1])

    def magicUp(self, ID):
        self.objects['user'].statistics['magic'] += int(self.statistics['itemEffect'][ID][1])
        if self.objects['user'].statistics['magic'] > self.objects['user'].statistics['maxMagic']:
            self.objects['user'].statistics['magic'] = self.objects['user'].statistics['maxMagic']
        print "You gained %d magic" % int(self.statistics['itemEffect'][ID][1])

    #Weapons
    def checkType(self, ID, type):
        """
        Weapon Types
        1 - Slashing
        2 - Piercing
        3 - Bludgeoning
        4 - Striking
        """
        if type == int(self.statistics['weaponType'][ID][0]):
            return 1
        else:
            return .5
    
    def setTypes(self):
        #self.types = {'None': 0, 'slashing': self.slashing, 'piercing': self.piercing}
        self.types = {}
        self.types['0'] = 0
        self.types['1'] = self.slashing
        self.types['2'] = self.piercing
        self.types['3'] = self.bludgeon
        self.types['4'] = self.strike
    
    def strike(self):
        print "You struck them with your %s" % self.objects['items'].statistics['names'][self.objects['user'].statistics['weapon']]
    
    def slashing(self):
        print "You slashed them with your %s" % self.objects['items'].statistics['names'][self.objects['user'].statistics['weapon']]
        if not int(self.objects['items'].statistics['weaponType'][self.objects['user'].statistics['weapon']][0]) == 1:
            print "Not as effective"
    
    def piercing(self):
        print "You stabbed them with your %s" % self.statistics['names'][self.objects['user'].statistics['weapon']]
        if not int(self.objects['items'].statistics['weaponType'][self.objects['user'].statistics['weapon']][0]) == 2:
            print "Not as effective"
            
    def bludgeon(self):
        print "You bludgeon them with your %s" % self.objects['items'].statistics['names'][self.objects['user'].statistics['weapon']]
    

class Magic(rpgObject):
    def __init__(self):
        rpgObject.__init__(self)
        self.readStats()
        
        self.statistics['spellEffects'] = ['', '', '', self.poison, self.paralyze, self.sleep]
        
    def readStats(self):
        openFile = 'text/spells.txt'
        data = open(openFile)
        self.addStat('magic', data.readlines())
        self.addStat('names', [])
        self.addStat('castWord', [])
        self.addStat('effects', [])
        self.addStat('cost', [])
        self.addStat('inBattle', [])
        self.addStat('description', [])

        tempStats = range(0, len(self.statistics['magic']))
        for stats in range(0, len(self.statistics['magic'])):
            tempStats[stats] = self.statistics['magic'][stats].split('|')
        for num in range(0, len(self.statistics['magic'])):
            self.statistics['names'].append(tempStats[num][1])
            self.statistics['castWord'].append(tempStats[num][2])
            self.statistics['effects'].append(tempStats[num][3].split(','))
            self.statistics['cost'].append(int(tempStats[num][4]))
            self.statistics['inBattle'].append(int(tempStats[num][5]))
            self.statistics['description'].append(tempStats[num][6])

            self.statistics['effects'][num][0] = int(self.statistics['effects'][num][0])
            self.statistics['effects'][num][1] = int(self.statistics['effects'][num][1])
        #print self.statistics['inBattle']

    def effects(self, ID):
        """
        1 - Damage
        2 - Healing
        3 - Poison
        4 - Paralyze
        5 - Sleep
        6 - Dazed
        7 - Confused
        """
        if self.objects['user'].statistics['magic'] >= self.statistics['cost'][ID]:
            self.objects['user'].statistics['magic'] -= self.statistics['cost'][ID]
            if self.statistics['effects'][ID][0] == 1:
                print self.statistics['description'][ID]
                print "Delt %d damage" % self.statistics['effects'][ID][1]
                self.objects['enemy'].statistics['health'] -= self.statistics['effects'][ID][1]
            if self.statistics['effects'][ID][0] == 2: 
                print self.statistics['description'][ID]
                print "Healed %d" % self.statistics['effects'][ID][1]
                self.objects['user'].statistics['health'] += self.statistics['effects'][ID][1]
                if self.objects['user'].statistics['health'] > self.objects['user'].statistics['maxHealth']:
                    self.objects['user'].statistics['health'] = self.objects['user'].statistics['maxHealth']
            if self.statistics['effects'][ID][0] == 3:
                print self.statistics['description'][ID]
                self.objects['enemy'].statistics['effect'] = [3, self.statistics['effects'][ID][1],self.statistics['effects'][ID][2]]
            if self.statistics['effects'][ID][0] == 4:
                print self.statistics['description'][ID]
                self.objects['enemy'].statistics['effect'] = [4, self.statistics['effects'][ID][1], 0]
            if self.statistics['effects'][ID][0] == 5:
                print self.statistics['description'][ID]
                turns = self.statistics['effects'][ID][1] + self.objects['user'].statistics['level']
                self.objects['enemy'].statistics['effect'] = [5, turns, 0]
        else:
            print "Not enough MP"

    def poison(self, whoPoisoned):
        print "Poisoned"
        whoPoisoned.statistics['health'] -= int(whoPoisoned.statistics['effect'][2])
        return 1
        
    def sleep(self, whoAsleep):
        print "Sleeping"
        return 0
    
    def paralyze(self, whoParalyzed):
        print "Payalyzed"
        unParalyze = 100 - whoParalyzed.statistics['dexterity']
        percent = random.randint(1,100)
        if percent >= unParalyze:
            return 1
        return 0

class Quest(rpgObject):
    def __init__(self):
        rpgObject.__init__(self)
        self.readStats()
        
        self.addStat('types', ['', self.blocked])
        
    def readStats(self):
        openFile = "text/quests.txt"
        data = open(openFile)
        self.addStat('quests', data.readlines())
        self.addStat('giver', [])
        self.addStat('requiredItem', [])
        self.addStat('experience', [])
        self.addStat('restriction', [])
        self.addStat('startingText', [])
        self.addStat('finishingText', [])
        tempStats = []
        
        for items in self.statistics['quests']:
            tempStats.append(items.split('|'))
         
        for quest in tempStats:
            self.statistics['giver'].append(quest[1])
            self.statistics['requiredItem'].append(int(quest[2]))
            self.statistics['restriction'].append(quest[3].split(','))
            self.statistics['experience'].append(int(quest[4]))
            self.statistics['startingText'].append(quest[5])
            self.statistics['finishingText'].append(quest[6])
            
    def give(self, questID, itemID):
        for item in self.objects['user'].statistics['inventory']:
            if itemID == item:
                if item == self.statistics['requiredItem'][questID]:
                    print "Given"
                    print self.statistics['finishingText'][questID]
                    print "Gained %d XP" % self.statistics['experience'][questID]
                    self.objects['user'].statistics['quests'][questID] = 1
                    self.objects['user'].statistics['inventory'].remove(item)
                    self.objects['user'].statistics['experience'] += self.statistics['experience'][questID]
                    self.objects['user'].levelUp()
                    return
                else:
                    print "Give %s to whom?" % self.objects['items'].statistics['names'][itemID]
                    return
        print "You don't have a %s" % self.objects['items'].statistics['names'][itemID]
        
    
    def printQuest(self, ID):
        print self.statistics['startingText'][ID]
        itemID = int(self.statistics['requiredItem'][ID])
        print "Required item: %s" % self.objects['items'].statistics['names'][itemID]
    
    def blocked(self, ID, args):
        if self.statistics['restriction'][ID][1] == args[1].split()[0]:
            print "You are stopped by %s" % self.statistics['giver'][ID]
            args[0] = -1
        return args[0]
        
        
class Shop(rpgObject):
    def __init__(self, db):
        rpgObject.__init__(self)
        
        self.cursor = db.db.cursor()
        #try:
        self.readStatsSQL()
        #except:
        #    self.readStats()

    def readStats(self):
        openFile = 'text/shops.txt'
        data = open(openFile)
        self.addStat('shops', data.readlines())
        self.addStat('owner', [])
        self.addStat('type', [])
        self.addStat('items', [])
        
        tempStats = []
        
        for items in self.statistics['shops']:
            tempStats.append(items.split('|'))
            
        for shop in tempStats:
            self.statistics['owner'].append(shop[1])
            self.statistics['type'].append(int(shop[2]))
            self.statistics['items'].append(map(int, shop[3].split(',')))
        
    def readStatsSQL(self):        
        sql = "SELECT * FROM stores"
        self.cursor.execute(sql)
        
        openFile = 'text/shops.txt'
        data = open(openFile, 'w')
        self.addStat('owner', [])
        self.addStat('type', [])
        self.addStat('items', [])
        dataToWrite = ""
        
        for row in self.cursor.fetchall():
            self.statistics['owner'].append(row[1])
            self.statistics['type'].append(int(row[2]))
            self.statistics['items'].append(map(int, row[3].split(',')))
            dataToWrite = dataToWrite + "\n" + "%s|%s|%s|%s|" % (row[0], row[1], row[2], row[3])
        
        dataToWrite = dataToWrite.strip("\n")
        
        data.write(dataToWrite)
        data.close()
        
    def buy(self, itemID):
        #sees if user has enough gold first
        if self.objects['user'].statistics['gold'] >= self.objects['items'].statistics['cost'][itemID]:
            print "You bought a %s" % self.objects['items'].statistics['names'][itemID]
            #adds the item to their inventory
            self.objects['user'].statistics['inventory'].append(itemID)
            #takes the gold
            self.objects['user'].statistics['gold'] -= self.objects['items'].statistics['cost'][itemID]
    
    def sell(self, itemID):
        print "You sold a %s" % self.objects['items'].statistics['names'][itemID]
        #removes the item
        self.objects['user'].statistics['inventory'].remove(itemID)
        #gives the gold to the user, but only 75% of the value
        self.objects['user'].statistics['gold'] += round(self.objects['items'].statistics['cost'][itemID] * .75)
    
    def list(self, shopID):
        #lists the items in the shop
        print "Welcome to my shop.  Please take a look:"
        for item in self.statistics['items'][shopID]:
            #cycles through the items that are in the shop, listing the gold and item name
            print "%dG- %s" % (self.objects['items'].statistics['cost'][int(item)], self.objects['items'].statistics['names'][int(item)])
            
class Database:
    def __init__(self):
        self.dbConnect()
    
    def dbConnect(self):
        host = '172.21.40.10'
        user = 'athedyn'
        password = ''
        database = 'athedyn'
        
        self.db = MySQLdb.connect(host, user, password, database)
        

if __name__ == "__main__":
    print "Please use main.py as it starts the game"